package router

import (
	"admin100/app/api"
	"admin100/app/api/loginnotice"
	"admin100/app/service"
	"admin100/app/service/filter"
	"admin100/library/define"
	"admin100/library/define/defLang"
	"admin100/library/response"

	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

func init() {
	s := g.Server()
	s.Group("/", func(group *ghttp.RouterGroup) {
		s.BindHookHandler("/*any", ghttp.HookBeforeServe, service.Middle.Ctx)
		s.BindHookHandler("/*any", ghttp.HookBeforeServe, filter.TrimParseFormAndSetSessionPostId)
		//s.BindHookHandler("/login", ghttp.HookBeforeServe, common.SetUid)

		s.Use(func(r *ghttp.Request) {
			defer func() {
				if err := r.GetError(); err != nil {
					r.Response.ClearBuffer()
					r.Response.Status = 200
					if gErr, ok := err.(*gerror.Error); ok {
						var (
							msg  = gErr.Error()
							code = define.ErrorCodeType(gErr.Code())
						)

						// 日志写入规则, 返给用户看的并不写入日志
						if gErr.Code() > 40000 && gErr.Code() < 50000 {
							//日志获取真实错误
							if gErr.Error() != defLang.GotMsg(code) {
								msg = defLang.GotMsg(code)
							}

							g.Log("sql").Error(gErr.Stack())
						} else if gErr.Code() > 60000 {
							g.Log().Error(gErr.Stack())
						}

						response.JsonExitWithMsg(r, define.ErrorCodeType(gErr.Code()), msg)
					} else {
						response.JsonExitWithMsg(r, define.TypeAssetErr, defLang.GotMsg(define.TypeAssetErr))
					}
				}
				r.Exit()
			}()

			r.Middleware.Next()
		})

		group.Middleware(
			service.Middle.IsDifferentLogin,
		)
		group.ALL("/", api.Login)
		group.Middleware(
			service.Middle.Auth,
		)

		// old case
		group.ALL("/index", api.Index)
		// 设置
		group.ALL("/role", api.RoleMgr)
		group.ALL("/user", api.UserMgr)
		group.ALL("/menu", api.MenuMgr)
		group.ALL("/player", api.PlayerMgr)
		group.ALL("/tool", api.ToolMgr)
		group.ALL("/tool/loginnotice", loginnotice.LoginNoticeMgr)
		group.ALL("/tool/promote", api.PromoteMgr)
		group.ALL("/log", api.LogMgr)
		group.ALL("/version", api.VersionMgr)

		// 数据和统计
		group.ALL("/statistics", api.StatisticsMgr)
		group.ALL("/resource", api.ResourceMgr)

		//设置-后台工具
		group.ALL("/msg-template", api.MsgTemplateMgrApi)
		group.ALL("/set-data", api.SettingDataMgrApi)
		group.ALL("/mail-smtp-data", api.MailSmtpDataMgrApi)
	})
}
